const apiWfScheme = window.$api.workflow.scheme;
const apiWfProcess = window.$api.workflow.process;

import mixin from "./form";
export default function() {
  return {
    mixins: [mixin()],
    created() {},
    props: {
      visible: {
        type: Boolean,
      },
      title: String,
      code: String,
      isLoadFormData: Boolean,
      params: {
        type: Object,
        default: () => {
          return {};
        },
      },
      type: String,

      isToken: false,

      wfIsPrints:Boolean
    },
    data() {
      return {
        // 流程信息
        wfscheme: {},
        wfData: [],
        currentNode: {},
        processId: "",
        parentProcessId: "",
        isChildProcess: false,
        processTitle: "",
        taskId: "",
        task: null,
        process: null,
        logs: [], // 流程日志信息
        nodeMap: {}, // 需要处理的任务
        userLogs: [], // 人员日志信息
        nodeLogs: [],
        taskBtns: [],

        activeName: "form",

        isWfReadOnly: false,

        wfSecretLevel: 4,

        wfPrintData:''
      };
    },
    computed: {
      hasForm() {
        if (this.isParent) {
          return false;
        }
        return this.isForm(this.currentNode);
      },
    },
    methods: {
      async handleOpened(showLoading, hideLoading) {
        showLoading && showLoading("加载流程信息...");
        this.processId = '';
        await this.loadWf();
        hideLoading && hideLoading();
      },
      handleClosed() {
        this.$emit("update:visible", false);
        this.activeName = "form";

        this.resetWfForm && this.resetWfForm();
        this.resetFormToMe && this.resetFormToMe();

        this.$emit("loadError");
      },
      showWfLoadError(data) {
        if (data == null) {
          this.$message({
            type: "error",
            message: this.$t("流程加载失败!"),
          });
          this.handleClosed();
          this.$emit('printDataLoaded','');
          return false;
        }
        return true;
      },
      async loadWf() {
        this.wfPrintData ='';
        // 加载流程信息
        let data = null;
        switch (this.type) {
          case "auditAndlook":
            if (this.params.loadProcessId) {
              this.processId = await this.params.loadProcessId();
              if (this.processId == "") {
                this.midVisible = false;
                this.$emit("error");
                return;
              }
            } else if (this.params.processId) {
              this.processId = this.params.processId;
            }
            data = await this.$awaitWraper(
              apiWfProcess.getTaskByProcessId(this.processId)
            );
            if (!this.showWfLoadError(data)) {
              return;
            }

            data.task = data.tasks.find(
              (t) => t.f_UserId == this.loginInfo.f_UserId
            );

            if (data.task) {
              this.taskId = data.task.f_Id;
            } else {
              this.isWfReadOnly = true;
            }

            if (data.task && data.task.f_Type == 3) {
              this.isChildProcess = true;
              this.parentProcessId = data.task.f_ProcessId;
            } else if (data.process.f_IsChild == 1) {
              // 如果是子流程
              this.parentProcessId = data.process.f_ParentProcessId;
              this.isChildProcess = true;
            } else {
              this.parentProcessId = "";
              this.isChildProcess = false;
            }

            this.process = data.process;
            this.task = data.task;

            this.setLogsAndTasks(data.logs || [], data.tasks || []);

            break;
          case "audit":
          case "look":
            this.taskId = this.params.taskId;
            if (!this.isToken) {
              data = await this.$awaitWraper(
                apiWfProcess.getTask(this.params.taskId)
              );
              if (!this.showWfLoadError(data)) {
                return;
              }
            } else {
              data = await this.$awaitWraper(
                apiWfProcess.GetTaskByToken(this.params.taskId)
              );
              if (!this.showWfLoadError(data)) {
                this.midVisible = false;
                return;
              }
              this.taskId = data.task.f_Id;
            }

            if (data.task.f_Type == 3) {
              this.isChildProcess = true;
              this.parentProcessId = data.task.f_ProcessId;
            } else if (data.process.f_IsChild == 1) {
              // 如果是子流程
              this.parentProcessId = data.process.f_ParentProcessId;
              this.isChildProcess = true;
            } else {
              this.parentProcessId = "";
              this.isChildProcess = false;
            }

            this.process = data.process;
            this.task = data.task;
            if (data.task.f_Type == 3) {
              this.processId = this.task.f_ChildProcessId;
            } else {
              this.processId = this.process.f_Id;
            }

            this.setLogsAndTasks(data.logs || [], data.tasks || []);
            break;
          case "lookmy":
            this.processId = this.params.processId;
            data = await this.$awaitWraper(
              apiWfProcess.get(this.params.processId)
            );
            if (!this.showWfLoadError(data)) {
              return;
            }
            if (data.process.f_IsChild == 1) {
              // 如果是子流程
              this.parentProcessId = data.process.f_ParentProcessId;
              this.isChildProcess = true;
            }
            this.process = data.process;

            this.processTitle = this.process.f_Title;
            this.setLogsAndTasks(data.logs, data.tasks);

            break;
          case "draft":
            this.processId = this.params.processId;
            data = await this.$awaitWraper(
              apiWfProcess.getDraft(this.params.processId)
            );
            if (!this.showWfLoadError(data)) {
              return;
            }
            this.process = data.process;
            this.wfSecretLevel = this.process.f_SecretLevel || 0;
            break;
          default:
            if (!this.processId) {
              this.processId = `${this.$uuid()}`; // 去掉 wf_
            }
            data = await this.$awaitWraper(apiWfScheme.get(this.code));
            if (!this.showWfLoadError(data)) {
              return;
            }
            this.wfSecretLevel = data.schemeinfo.f_SecretLevel;
            this.processTitle =  data.schemeinfo.f_Name;
            break;
        }

        const { scheme } = data;
        this.wfscheme = JSON.parse(scheme.f_Content);
        const { wfData } = this.wfscheme;
        wfData.forEach((item) => {
          const node = this.nodeMap[item.id];
          if (
            node &&
            (item.strokeColor == undefined || item.strokeColor == "#000")
          ) {
            if (node.find((t) => !t.isFinish && !t.isRead)) {
              item.strokeColor = "#409EFF";
            } else {
              if (node.filter((t) => !t.isRead)[0].isAgree == 0) {
                item.strokeColor = "#f56c6c";
              } else {
                item.strokeColor = "#67C23A";
              }
            }

            if (node.find((t) => t.isFinish)) {
              item.hasFinish = true;
            }
          }
        });
        this.wfData = wfData;
        this.setForm && this.setForm(data);

        const startNode = this.wfData.find((t) => t.type == "startEvent");
        if (!startNode.name) {
          startNode.name = this.$t("开始节点");
        }

        if (this.currentNode.isInherit) {
          // 如果是继承表单就开始节点的表单信息

          this.currentNode.formWrodPrintCode = startNode.formWrodPrintCode;
          this.currentNode.formType = startNode.formType;
          this.currentNode.formVerison = startNode.formVerison;
          this.currentNode.formRelationId = startNode.formRelationId;
          this.currentNode.formUrl = startNode.formUrl;
          this.currentNode.authFields = startNode.authFields;
        }

        if (this.hasForm) {
          await this.loadForm(
            this.currentNode,
            this.processId,
            this.params,
            this.isLoadFormData,
            ["look", "lookmy"].includes(this.type) ||
              (this.type == "auditAndlook" && this.task == null)
          );

          if (this.hasWfForm == false) {
            this.activeName = "wfinfo";
            this.handleTabClick();
          }
          else{
            if(this.wfIsPrints){
              if(this.currentNode.formWrodPrintCode){
                this.wfPrintData = await this.$refs.wordprintBtn.getHtml()
              }
            }
          }

        } else {
          this.activeName = "wfinfo";
          this.handleTabClick();
        }

        this.$emit('printDataLoaded',this.wfPrintData);
        
      },
      setLogsAndTasks(logs, tasks) {
        const res = [];
        const taskMap = {};
        const nodeMap = {};
        const userLogs = [];

        tasks.forEach((task) => {
          let desEx = `【${this.$t("处理中,开始时间")}:${this.lr_dateFormat(
            task.f_CreateDate
          )},${this.$t("已进行")}:${this.$calcDateText(
            task.f_CreateDate,
            this.$getDayTime()
          )}】`;

          nodeMap[task.f_UnitId] = nodeMap[task.f_UnitId] || [
            {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: `${this.$t("正在审核")}`,
              desEx,
              time: `${this.$t("当前-创建时间")}:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
              isFinish: false,
            },
          ];

          if (task.f_Type == 2) {
            taskMap[task.f_UnitId + task.f_Type] = taskMap[
              task.f_UnitId + task.f_Type
            ] || {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: `${this.$t("正在查阅")}`,
              desEx,
              time: `${this.$t("当前-创建时间")}:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
              isRead: true,
            };
            taskMap[task.f_UnitId + task.f_Type].userIds.push(task.f_UserId);

            if (nodeMap[task.f_UnitId].length == 1) {
              nodeMap[task.f_UnitId].push({
                unitId: task.f_UnitId,
                name: task.f_UnitName,
                userIds: [],
                des: this.$t(`正在查阅`),
                desEx,
                time: `${this.$t("当前-创建时间")}:${this.lr_dateFormat(task.f_CreateDate)}`,
                type: "primary",
                isRead: true,
              });
            }
            nodeMap[task.f_UnitId][1].userIds.push(task.f_UserId);
          } else if (task.f_Type == 3 && task.f_State == 8) {
            taskMap[task.f_UnitId] = taskMap[task.f_UnitId] || {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: this.$t(`子流程审核中`),
              desEx,
              time: `${this.$t("当前-创建时间")}:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
              taskType: 3,
              childProcessId: task.f_ChildProcessId,
            };
            taskMap[task.f_UnitId].userIds.push(task.f_UserId);
            nodeMap[task.f_UnitId][0].taskType = 3;
            nodeMap[task.f_UnitId][0].des = this.$t("子流程审核中");
            nodeMap[task.f_UnitId][0].childProcessId = task.f_ChildProcessId;
            nodeMap[task.f_UnitId][0].userIds.push(task.f_UserId);
          } else if (task.f_Type == 3 && task.f_State == 1) {
            taskMap[task.f_UnitId] = taskMap[task.f_UnitId] || {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: this.$t(`正在提交子流程`),
              desEx,
              time: `${this.$t("当前-创建时间")}:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
            };
            taskMap[task.f_UnitId].userIds.push(task.f_UserId);
            nodeMap[task.f_UnitId][0].des = this.$t("正在提交子流程");
            nodeMap[task.f_UnitId][0].userIds.push(task.f_UserId);
          } else {
            taskMap[task.f_UnitId] = taskMap[task.f_UnitId] || {
              unitId: task.f_UnitId,
              name: task.f_UnitName,
              userIds: [],
              des: this.$t(`正在审核`),
              desEx,
              time: `${this.$t("当前-创建时间")}:${this.lr_dateFormat(task.f_CreateDate)}`,
              type: "primary",
            };
            taskMap[task.f_UnitId].userIds.push(task.f_UserId);
            nodeMap[task.f_UnitId][0].userIds.push(task.f_UserId);
          }
        });

        for (let key in taskMap) {
          res.push(taskMap[key]);
        }

        for (let key in nodeMap) {
          nodeMap[key] = nodeMap[key].filter((t) => t.userIds.length > 0);
        }
        console.log(logs, "wf logs ");
        logs.forEach((log) => {
          let des = log.f_Des ? log.f_Des : log.f_OperationName;
          let desEx = "";
          if (log.f_TaskCreateDate) {
            desEx += `【${this.$t("已处理,审核开始时间")}:${this.lr_dateFormat(
              log.f_TaskCreateDate
            )},${this.$t("审核结束时间")}:${this.lr_dateFormat(
              log.f_CreateDate
            )},${this.$t("审核时长")}:${this.$calcDateText(
              log.f_TaskCreateDate,
              log.f_CreateDate
            )}】`;
          }

          res.push({
            unitId: log.f_UnitId,
            name: log.f_UnitName,
            userIds: [log.f_UserId],
            des: des,
            desEx,
            time: this.lr_dateFormat(log.f_CreateDate),
            taskType: log.f_TaskType,
            childProcessId: log.f_ChildProcessId,
            isShowUser: log.f_OperationCode == "createsub",
            type: "info",
          });

          nodeMap[log.f_UnitId] = nodeMap[log.f_UnitId] || [];
          nodeMap[log.f_UnitId].push({
            unitId: log.f_UnitId,
            name: log.f_UnitName,
            userIds: [log.f_UserId],
            time: this.lr_dateFormat(log.f_CreateDate),
            des: log.f_Des ? log.f_Des : log.f_OperationName,
            desEx,
            taskType: log.f_TaskType,
            childProcessId: log.f_ChildProcessId,
            isShowUser: log.f_OperationCode == "createsub",
            type: "info",
            isFinish: true,
            isAgree: log.f_IsAgree,
          });

          if (log.f_TaskType == 1 && !["sign"].includes(log.f_OperationCode)) {
            // 右侧显示审核记录
            const userLogIndex = userLogs.findIndex(
              (t) => t.id == log.f_UnitId
            );
            if (userLogIndex == -1) {
              userLogs.push({
                id: log.f_UnitId,
                name: log.f_UnitName,
                user: log.f_UserName,
                time: this.lr_dateFormat(log.f_CreateDate),
                des: log.f_Des,
                img: log.f_StampImg,
                file: log.f_FileId,
              });
            }
          }
        });

        this.logs = res;
        this.nodeMap = nodeMap;

        this.userLogs = userLogs.sort(function(a, b) {
          return b.time < a.time ? -1 : 1;
        });
      },

      handleTabClick() {
        if (this.activeName == "wfinfo") {
          this.$nextTick(() => {
            //console.log(this.wfData, "this.wfData");
            this.$refs.bflow && this.$refs.bflow.setData(this.$deepClone(this.wfData));
          });
        }
      },

      isForm(node) {
        if (node.isInherit) {
          node = this.wfData.find((t) => t.type == "startEvent");
        }

        const { formType, formVerison, formUrl } = node;
        if (formType == "1") {
          if (!formVerison) {
            return false;
          }
        } else {
          if (!formUrl) {
            return false;
          }
        }
        return true;
      },
      isFormById(id) {
        const node = this.wfData.find((t) => t.id == id);
        if (node) {
          return this.isForm(node);
        } else {
          return false;
        }
      },

      async getPrintData() {
        if (!this.hasWfForm || !this.$refs.wfForm) {
          return {};
        }
        const formData = await this.$refs.wfForm.getPrintData();

        if (this.userLogs) {
          this.userLogs.forEach((log) => {
            const p = "WF";
            formData[`${p}Des${log.id}`] = log.des;
            formData[`${p}Name${log.id}`] = log.name;
            formData[`${p}User${log.id}`] = log.user;
            formData[`${p}Time${log.id}`] = log.time;
          });
        }
        return formData;
      },
    },
  };
}
